//
//  LYLocationManager.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/25.
//

import UIKit
import CoreLocation
import SystemConfiguration.CaptiveNetwork
import NetworkExtension

class LYLocationManager: NSObject, CLLocationManagerDelegate {
    private var locationManager = CLLocationManager()
    private var isAlertViewShowing: Bool = false
    private var currentLocation: CLLocation?
    private var currentPlacemark: CLPlacemark?
    private var completion: ((LocationInfo?) -> Void)?
    static let shared = LYLocationManager()
    var alertView: LYCustomAlertView? = nil
    // 位置信息结构体
    struct LocationInfo {
        var latitude: Double
        var longitude: Double
        var countryCode: String?
        var country: String?
        var province: String?
        var city: String?
        var district: String?
        var street: String?
        var formattedAddress: String?
    }
    
    override init() {
        super.init()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
    }
     
    // 请求定位权限（兼容 iOS 13）
    func requestLocationPermission(_ completion: ((Bool) -> Void)? = nil) {
        let status = CLLocationManager.authorizationStatus()
        
        switch status {
        case .notDetermined:
            locationManager.requestWhenInUseAuthorization()
            completion?(false)
        case .denied, .restricted:
            print("定位权限被拒绝，引导用户去设置开启")
            showAlertView()
            completion?(false)
        case .authorizedWhenInUse, .authorizedAlways:
            startUpdatingLocation()
            completion?(true)
        @unknown default:
            completion?(false)
        }
    }
    
    // 获取完整位置信息
    func getFullLocationInfo(completion: @escaping (LocationInfo?) -> Void) {
        self.completion = completion
        requestLocationPermission { [weak self] granted in
            if granted {
                self?.startUpdatingLocation()
            } else {
                completion(nil)
            }
        }
    }
    
    // 开始获取位置
    private func startUpdatingLocation() {
        locationManager.startUpdatingLocation()
    }
    
    private func showAlertView() {
        guard appCountryEnv == .indonesia else { return }
        
        if let alertView = self.alertView,
           alertView.isShowingAlert == true {
            return
        }
        let alert = LYCustomAlertView(
            title: LYlocalizedString(""),
            message: LYlocalizedString("LocationWhenInUseUsageDescription")
        )
        
        let stopButton = LYCustomAlertViewAction.getButton(with: LYlocalizedString("Stop"),
                                                         actionType: .unObvious)
        
        let confirmButton = LYCustomAlertViewAction.getButton(with: LYlocalizedString("Open setting"),
                                                         actionType: .obvious)
    
        alert.addButton(stopButton) {
            alert.hide()
        }
        alert.addButton(confirmButton) {
            alert.hide { [weak self] in
                self?.openAppSettings()
            }
        }
        
        alert.show()
        self.alertView = alert
    }
    
    private func openAppSettings() {
        if let url = URL(string: UIApplication.openSettingsURLString) {
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
    }
    
    // MARK: - WiFi 相关功能
    /// 获取当前WiFi信息（自动处理权限和兼容性）
    func getCurrentWifiInfo(completion: @escaping (WifiInfo?) -> Void) {
        // 先检查定位权限状态（iOS 13+需要）
        let status = CLLocationManager.authorizationStatus()
        
        if #available(iOS 13.0, *), status == .denied {
            print("需要定位权限才能获取WiFi信息")
            showWifiPermissionAlert()
            completion(nil)
            return
        }
        
        // iOS 14+优先使用新API
        if #available(iOS 14.0, *) {
            fetchWifiInfoWithNEHotspotNetwork(completion: completion)
        } else {
            fetchWifiInfoWithCNCopy(completion: completion)
        }
    }
    
    /// WiFi信息结构体
    struct WifiInfo {
        var ssid: String?
        var bssid: String?
        var signalStrength: Int? // 信号强度（可选）
    }
    
    // MARK: - 私有方法
    
    @available(iOS 14.0, *)
    private func fetchWifiInfoWithNEHotspotNetwork(completion: @escaping (WifiInfo?) -> Void) {
        NEHotspotNetwork.fetchCurrent { [weak self] hotspotNetwork in
            guard let network = hotspotNetwork else {
                print("NEHotspotNetwork获取失败")
                self?.fallbackToCNCopy(completion: completion)
                return
            }
            
            let info = WifiInfo(
                ssid: network.ssid,
                bssid: network.bssid,
                signalStrength: nil // 此API无法获取信号强度
            )
            completion(info)
        }
    }
    
    private func fetchWifiInfoWithCNCopy(completion: @escaping (WifiInfo?) -> Void) {
        DispatchQueue.global().async { [weak self] in
            var ssid: String?
            var bssid: String?
            
            if let interfaces = CNCopySupportedInterfaces() as? [String] {
                for interface in interfaces {
                    guard let info = CNCopyCurrentNetworkInfo(interface as CFString) as? [String: Any] else {
                        continue
                    }
                    ssid = info[kCNNetworkInfoKeySSID as String] as? String
                    bssid = info[kCNNetworkInfoKeyBSSID as String] as? String
                    break
                }
            }
            
            DispatchQueue.main.async {
                if ssid != nil || bssid != nil {
                    completion(WifiInfo(ssid: ssid, bssid: bssid, signalStrength: nil))
                } else {
                    print("CNCopyCurrentNetworkInfo获取失败")
                    completion(nil)
                }
            }
        }
    }
    
    private func fallbackToCNCopy(completion: @escaping (WifiInfo?) -> Void) {
        if #available(iOS 14.0, *) {
            // 如果NEHotspotNetwork失败，尝试旧方法
            fetchWifiInfoWithCNCopy(completion: completion)
        } else {
            completion(nil)
        }
    }
    
    private func showWifiPermissionAlert() {
//        let alert = UIAlertController(
//            title: "需要位置权限",
//            message: "请前往设置允许访问位置权限以获取WiFi信息",
//            preferredStyle: .alert
//        )
//        
//        alert.addAction(UIAlertAction(title: "取消", style: .cancel))
//        alert.addAction(UIAlertAction(title: "去设置", style: .default) { _ in
//            self.openAppSettings()
//        })
//        
//        if let topVC = UIApplication.shared.topViewController() {
//            topVC.present(alert, animated: true)
//        }
    }

    
    // MARK: - 反向地理编码获取地址信息
    private func reverseGeocodeLocation(_ location: CLLocation) {
        let geocoder = CLGeocoder()
        geocoder.reverseGeocodeLocation(location) { [weak self] (placemarks, error) in
            guard let self = self else { return }
            
            if let error = error {
                print("反向地理编码失败: \(error.localizedDescription)")
                self.completion?(nil)
                return
            }
            
            guard let placemark = placemarks?.first else {
                self.completion?(nil)
                return
            }
            
            self.currentPlacemark = placemark
            let locationInfo = self.createLocationInfo(from: placemark, location: location)
            self.completion?(locationInfo)
        }
    }
    
    private func createLocationInfo(from placemark: CLPlacemark, location: CLLocation) -> LocationInfo {
        return LocationInfo(
            latitude: location.coordinate.latitude,
            longitude: location.coordinate.longitude,
            countryCode: placemark.isoCountryCode,
            country: placemark.country,
            province: placemark.administrativeArea,
            city: placemark.locality ?? placemark.administrativeArea,
            district: placemark.subLocality,
            street: placemark.thoroughfare,
            formattedAddress: formatAddress(from: placemark)
        )
    }
    
    private func formatAddress(from placemark: CLPlacemark) -> String? {
        var addressComponents = [String]()
        
        if let thoroughfare = placemark.thoroughfare {
            addressComponents.append(thoroughfare)
        }
        if let subLocality = placemark.subLocality {
            addressComponents.append(subLocality)
        }
        if let locality = placemark.locality {
            addressComponents.append(locality)
        }
        if let administrativeArea = placemark.administrativeArea {
            addressComponents.append(administrativeArea)
        }
        if let country = placemark.country {
            addressComponents.append(country)
        }
        
        return addressComponents.isEmpty ? nil : addressComponents.joined(separator: ", ")
    }
    
    // MARK: - CLLocationManagerDelegate
    
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        requestLocationPermission()
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        
        // 停止更新以节省电量
        manager.stopUpdatingLocation()
        
        // 保存当前位置
        currentLocation = location
        
        // 打印经纬度
        print("当前位置：纬度 \(location.coordinate.latitude), 经度 \(location.coordinate.longitude)")
        
        LYUserDefaults.shared.setDouble(location.coordinate.latitude, forKey: latitudeKey)
        LYUserDefaults.shared.setDouble(location.coordinate.longitude, forKey: longitudeKey)
        // 进行反向地理编码获取地址信息
        reverseGeocodeLocation(location)
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("定位失败：\(error.localizedDescription)")
        completion?(nil)
    }
}
